//
//  SettingViewController.m
//  cityCar
//
//  Created by yao on 14-10-29.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SettingViewController.h"
#import "SettingCell.h"
#import "AreaViewController.h"
#import "AboutUsViewController.h"
#import "CityName.h"

@interface SettingViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, retain)UITableView *myTableView;
// 夜间模式开关
@property(nonatomic, retain)UISwitch *switchs1;
// 推送设置开关
@property(nonatomic, retain)UISwitch *switchs2;
@property(nonatomic, retain)UIAlertView *alert;
@end

@implementation SettingViewController

- (void)dealloc
{
    [_myTableView release];
    [_switchs1 release];
    [_switchs2 release];
    // 移除通知中心
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        // 创建通知中心，监控caches文件夹大小
        NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
        [notiCenter addObserver:self selector:@selector(receiveNotificate:) name:@"缓存" object:nil];
        [notiCenter addObserver:self selector:@selector(notiCenterAction:) name:@"CityName" object:nil];

    }
    return self;
}
- (void)receiveNotificate:(NSNotification *)noti
{
    // 收到通知后执行的方法 弹出清理成功的提示框
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"清理成功" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alert show];
    [alert release];
}
#pragma mark 地区的消息
- (void)notiCenterAction:(NSNotification *)noti
{    
    CityName *city = noti.object;    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
    
    SettingCell *cell = (SettingCell *)[self.myTableView cellForRowAtIndexPath:indexPath];
    cell.label1.text = city.city;
    
}
#pragma mark -
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [WebColor whiteSmoke];
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    self.cachSize = [self folderSizeAtPath:cachPath];
    [self setupView];
}
// 通常用于删除缓存的时，计算缓存大小
// 单个文件的大小
- (long long) fileSizeAtPath:(NSString*) filePath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
//遍历文件夹获得文件夹大小，返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

- (void)setupView
{
    self.myTableView.rowHeight = 50;
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(55, 55, self.view.frame.size.width - 60, self.view.frame.size.height - 100) style:UITableViewStylePlain];
    self.myTableView.backgroundColor = [WebColor whiteSmoke];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.view addSubview:self.myTableView];
    [_myTableView release];
    self.switchs1 = [[UISwitch alloc] initWithFrame:CGRectMake(200, 10, 60, 15)];
    self.switchs2 = [[UISwitch alloc] initWithFrame:CGRectMake(200, 10, 60, 15)];

    
    // 隐藏cell线条
    [self.myTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.switchs1 addTarget:self action:@selector(getValue1:) forControlEvents:UIControlEventValueChanged];
    [self.switchs2 addTarget:self action:@selector(getValue2:) forControlEvents:UIControlEventValueChanged];

}

// 夜间模式
- (void)getValue1:(UISwitch *)switchs
{
    if (switchs.isOn == YES) {
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center postNotificationName:@"theNight" object:@"on"];
    } else {
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center postNotificationName:@"theNight" object:@"off"];
    }
}
- (void)getValue2:(UISwitch *)switchs
{
    if (switchs.isOn == YES) {
        self.alert = [[UIAlertView alloc] initWithTitle:@"抱歉" message:@"该功能暂未实现" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [self.alert show];
        [_alert release];
    }
}
#pragma mark - tableView 协议
// 每个section中cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 2;
    } else if (section == 2) {
        return 3;
    } else {
        return 0;
    }
}
// tableView设置Cell的格式 方框
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    ForumDetailCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if ([cell respondsToSelector:@selector(tintColor)]) {
        
        CGFloat cornerRadius = 5.f;
        cell.backgroundColor = [UIColor clearColor];
        CAShapeLayer *layer = [[CAShapeLayer alloc] init];
        CGMutablePathRef pathRef = CGPathCreateMutable();
        CGRect bounds = CGRectInset(cell.bounds, 10, 0);
        // 一般要－20，由于当前页tableview横坐标起始点是55，所以要－75
        bounds.size.width = self.view.bounds.size.width - 75;
        
        BOOL addLine = NO;
        if (indexPath.row == 0 && indexPath.row == [tableView numberOfRowsInSection:indexPath.section] - 1) {
            CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
        } else if (indexPath.row  == 0) {
            
            CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
            CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
            addLine = YES;
        } else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
            
            CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
            CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
        } else {
            
            CGPathAddRect(pathRef, nil, bounds);
            addLine = YES;
        }
        layer.path = pathRef;
        CFRelease(pathRef);
        layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;
        layer.strokeColor = [UIColor lightGrayColor].CGColor;
        
        if (addLine == YES) {
            
            CALayer *lineLayer = [[CALayer alloc] init];
            CGFloat lineHeight = (1.f / [UIScreen mainScreen].scale);
            lineLayer.frame = CGRectMake(CGRectGetMinX(bounds)+10, bounds.size.height-lineHeight, bounds.size.width-10, lineHeight);
            lineLayer.backgroundColor = tableView.separatorColor.CGColor;
            [layer addSublayer:lineLayer];
        }
        
        UIView *testView = [[UIView alloc] initWithFrame:bounds];
        [testView.layer insertSublayer:layer atIndex:0];
        testView.backgroundColor = UIColor.clearColor;
        cell.backgroundView = testView;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SettingCell *cell1 = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (!cell1) {
        cell1 = [[[SettingCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"] autorelease];
    }
 
    switch (indexPath.section) {
        case 0:
        {
            if (indexPath.row == 0) {
                cell1.label.text = @"问题反馈";
                [cell1.myImageView setImage:[UIImage imageNamed:@"wenti.png"]];
                cell1.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
        }
            break;
        case 1:
        {
            cell1.selectionStyle = 0;
            if (indexPath.row == 0) {
                cell1.label.text = @"夜间模式";
                [cell1.myImageView setImage:[UIImage imageNamed:@"yejian.png"]];
                [cell1.contentView addSubview:self.switchs1];
            } else if (indexPath.row == 1) {
                cell1.label.text = @"推送设置";
                [cell1.myImageView setImage:[UIImage imageNamed:@"tuisong.png"]];
                [cell1.contentView addSubview:self.switchs2];
            }
        }
            break;
        case 2:
        {
            if (indexPath.row == 0) {
                cell1.label.text = @"地区设定";
                [cell1.myImageView setImage:[UIImage imageNamed:@"diqu.png"]];
                cell1.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//                cell1.label1.text = @"大连";
                // 先从本地读取
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentPath = [paths lastObject];
                NSString *arrPath = [documentPath stringByAppendingPathComponent:@"area.xml"];
                NSArray *readArr = [NSArray arrayWithContentsOfFile:arrPath];
//                NSLog(@"读取本地地区：%@", readArr);
                
                // 判断有就先从本地读取~
                if (readArr == nil) {
                    cell1.label1.text = @"大连";
                } else {
                    cell1.label1.text = [readArr lastObject];
                }

                
            } else if (indexPath.row == 1) {
                cell1.label.text = @"清理缓存";
                [cell1.myImageView setImage:[UIImage imageNamed:@"qingli.png"]];
                cell1.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell1.label1.text = [NSString stringWithFormat:@"%.1fM", self.cachSize];
            } else {
                cell1.label.text = @"关于我们";
                [cell1.myImageView setImage:[UIImage imageNamed:@"guanyu.png"]];
                cell1.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
        }
            break;
        default:
            break;
    }
    return cell1;
}
// section的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
// section的个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//    tableView.sectionIndexBackgroundColor = [WebColor whiteSmoke];
    return 3;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消cell的点中效果。
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 0:
        {
            if (indexPath.row == 0) {
                [self sendEMail];
//                FeedbackViewController *feedback = [[FeedbackViewController alloc] init];
//                [self presentViewController:feedback animated:YES completion:^{
//                    
//                }];
            }
        }
            break;
        case 1:
        {
            if (indexPath.row == 0) {
            } else if (indexPath.row == 1) {
            }
        }
            break;
        case 2:
        {
            if (indexPath.row == 0) {
//#warning 地区block
                AreaViewController *area = [[AreaViewController alloc] init];
                [self presentViewController:area animated:YES completion:^{
                    
                }];
                
                [area release];
            } else if (indexPath.row == 1) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"确认清除?" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                [alertView show];
                [alertView release];

                
            } else {
                AboutUsViewController *aboutUs = [[AboutUsViewController alloc] init];
                [self presentViewController:aboutUs animated:YES completion:^{
                    
                }];
                [aboutUs release];
            }
        }
            break;
        default:
            break;
    }


}
//-(void)displayComposerSheet
//{
//    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
//    picker.mailComposeDelegate = self;
//    
//    [picker setSubject:@"反馈意见"];
//    
//    // Set up recipients
//    NSArray *toRecipients = [NSArray arrayWithObject:@"m15040643061@163.com"];
//    
//    [picker setMessageBody:@"请输入" isHTML:YES];
//
//    [picker setToRecipients:toRecipients];
//    
//    // Attach an image to the email
//    //    NSString *path = [[NSBundle mainBundle] pathForResource:@"" ofType:@"png"];
//    //    NSData *myData = [NSData dataWithContentsOfFile:path];
//    //    [picker addAttachmentData:myData mimeType:@"image/png" fileName:@""];
//    
//    // Fill out the email body text
//    
//    [self presentViewController:picker animated:YES completion:nil];
//    
//}
- (void) alertWithTitle: (NSString *)_title_ msg: (NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:_title_
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}
//// 邮件发送相关提示
//- (void)mailComposeController:(MFMailComposeViewController *)controller
//          didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
//{
//    NSString *msg;
//    
//    switch (result)
//    {
//        case MFMailComposeResultCancelled:
//            msg = @"邮件发送取消";
//            break;
//        case MFMailComposeResultSaved:
//            msg = @"邮件保存成功";
//            [self alertWithTitle:nil msg:msg];
//            break;
//        case MFMailComposeResultSent:
//            msg = @"邮件发送成功";
//            [self alertWithTitle:nil msg:msg];
//            break;
//        case MFMailComposeResultFailed:
//            msg = @"邮件发送失败";
//            [self alertWithTitle:nil msg:msg];
//            break;
//        default:
//            break;
//    }
//    [self dismissViewControllerAnimated:YES completion:nil];
//    
//    // ios6.0
////    [self dismissModalViewControllerAnimated:YES];
//}

//点击按钮后，触发这个方法
-(void)sendEMail
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    
    if (mailClass != nil)
    {
        if ([mailClass canSendMail])
        {
            [self displayComposerSheet];
        }
        else
        {
            [self launchMailAppOnDevice];
        }
    }
    else
    {
        [self launchMailAppOnDevice];
    }
}
//可以发送邮件的话
-(void)displayComposerSheet
{
    MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
    
    mailPicker.mailComposeDelegate = self;
    
    //设置主题
    [mailPicker setSubject: @"反馈意见"];
    
    // 添加发送者
    NSArray *toRecipients = [NSArray arrayWithObject: @"15040643061@163.com"];
    
    //NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
    //NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com", nil];
    [mailPicker setToRecipients: toRecipients];
    //[picker setCcRecipients:ccRecipients];
    //[picker setBccRecipients:bccRecipients];
    
    // 添加图片
    //    UIImage *addPic = [UIImage imageNamed: @"123.jpg"];
    //    NSData *imageData = UIImagePNGRepresentation(addPic);            // png
    // NSData *imageData = UIImageJPEGRepresentation(addPic, 1);    // jpeg
    //    [mailPicker addAttachmentData: imageData mimeType: @"" fileName: @"123.jpg"];
    
    NSString *emailBody = @"请输入";
    [mailPicker setMessageBody:emailBody isHTML:YES];
    //ios6.0
//    [self presentModalViewController: mailPicker animated:YES];
    [self presentViewController:mailPicker animated:YES completion:nil];
    [mailPicker release];
}
-(void)launchMailAppOnDevice
{
    NSString *recipients = @"15040643061@163.com";
    //@"mailto:first@example.com?cc=second@example.com,third@example.com&subject=my email!";
    NSString *body = @"请输入";
    
    NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
    email = [email stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    NSString *msg;
    
    switch (result)
    {
        case MFMailComposeResultCancelled:
            msg = @"邮件发送取消";
            break;
        case MFMailComposeResultSaved:
            msg = @"邮件保存成功";
            [self alertWithTitle:nil msg:msg];
            break;
        case MFMailComposeResultSent:
            msg = @"邮件发送成功";
            [self alertWithTitle:nil msg:msg];
            break;
        case MFMailComposeResultFailed:
            msg = @"邮件发送失败";
            [self alertWithTitle:nil msg:msg];
            break;
        default:
            break;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    //ios6.0
//    [self dismissModalViewControllerAnimated:YES];
}





//根据被点击按钮的索引处理点击事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //                清理缓存的代码如下：
    if (buttonIndex == 1) {
        dispatch_async(
                       dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                       , ^{
                           NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
                           NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                           NSLog(@"files :%d",[files count]);
                           for (NSString *p in files) {
                               NSError *error;
                               NSString *path = [cachPath stringByAppendingPathComponent:p];
                               if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                   [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                               }
                           }
                       });
        NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
        [notiCenter postNotificationName:@"缓存" object:[NSString stringWithFormat:@"%.1fM", self.cachSize] userInfo:nil];
    } else if (buttonIndex == 0) {
        if ([alertView isEqual:self.alert]) {
            [self.switchs2 setOn:NO animated:YES];
        }
//        刷新caches文件夹大小数据 给cachSize赋值
        [self.myTableView reloadData];
        NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
        self.cachSize = [self folderSizeAtPath:cachPath];
    }
    
    NSLog(@"clickButtonAtIndex:%d",buttonIndex);
}
- (void)viewDidAppear:(BOOL)animated
{
    [self.myTableView reloadData];
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];

    self.cachSize = [self folderSizeAtPath:cachPath];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
